<?php
namespace app\api\controller;

use app\common\model\ArticleCollectModel;
use app\common\model\ArticleModel;
use app\common\model\CarLicenseMoreModel;
use app\common\model\CarModel;
use app\common\model\CarSeriesModel;
use app\common\model\MemberModel;
use app\common\model\UserActionModel as UserAction;
use app\common\model\UserActionModel;
use app\common\model\UserCarModel;
use app\common\model\UserCollectModel;
use app\common\model\UserCarMessageModel;
use app\common\model\ArticleMessageModel;

use think\facade\Cache;
use think\Request;

class MessageController extends BaseController{


    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(Request $request){
        return backError("用户名错误！");
    }

    /**
     * 获取留言列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getList(Request $request){
        $user = $request->user;
        $user = model("member")->find(5);
        if(empty($user)){
            return backError("用户未登陆");
        }
        $where[] = ["user_id","=",$user['uid']];
        $where[] = ["userCar.status","<>",-1];
        $user_car_list = db::view("userCar","*")
            ->view("CarSeries","series_name","userCar.series_id = CarSeries.series_id")
            ->page(1,5)
            ->where($where)->select();
        $user_car_id = array_column($user_car_list,"id");
        $message_list = model("userCarMessage")
            ->where(["user_car_id"=>["in",implode(",",$user_car_id)]])
            ->select();
        foreach($user_car_list as $k=>$v){
            $key = $v["id"];
            $user_car_list[$k]["message"] = [];
            foreach ($message_list as $val){
                if($val["user_car_id"] == $key){
                    $user_car_list[$k]["message"][] = $val;
                }
            }
        }
        return backSuccess($user_car_list,"ok");
    }

    public function getList2(Request $request){
        $user = $request->user;
        $page = $request->page ?: 1;
        $user = model("member")->find(6);
        if(empty($user)){
            return backError("用户未登陆");
        }
        $message_list = db::view("userCarMessage","*")
            ->view("UserCar","*","userCarMessage.user_car_id = UserCar.id")
            ->view("Car","car_name","UserCar.car_id = Car.car_id")
            ->where(["userCarMessage.user_id"=>$user['uid']])
            ->page($page,5)
            ->select();
        return backSuccess($message_list,"ok");
    }

    /**
     * 文章列表
     * @param Request $request
     * @param cat 分类标识
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function articleList(Request $request){
        $cat = $request->cat;
        $pageCount = $request->pageCount;
        $keyword = $request->keyword;
        if(empty($cat)){
            return backError("参数错误！");
        }
        $where=null;

        if(!empty($keyword)) $where["title"]=$keyword;
        if($cat==-1) $cat=0;

        $list=ArticleModel::getList($cat,$pageCount,$where);

        if(!empty($list['status'])){
            return backError("参数错误！");
        }

        return backSuccess($list);
    }

    /**
     * 文章详情
     * @param int id 文章ID
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function details(Request $request){
        $id = intval($request->id);
        if(empty($id)){
            return backError("文章ID错误");
        }

        $info=ArticleModel::getDetails($id);

        $info["collectStatus"]=0;
        $info["goodStatus"]=0;
        if(!empty($request->token)){
            $user_id=$request->user["uid"];

            $info["collectStatus"] = ArticleCollectModel::where('article_id', $info["article_id"])
                ->where("user_id", $user_id)
                ->where("status", ArticleCollectModel::SHOW_STATUS)
                ->count();

            $info["goodStatus"]=UserAction::checkGood($user_id,$id,1);
        }


        $info["msgCount"] = ArticleMessageModel::where('article_id', $info["article_id"])
            ->where("status", ArticleMessageModel::SHOW_STATUS)
            ->count();

        if(empty($info)){
            return backError("未找到文章");
        }
        return backSuccess($info);
    }
    /**
     * 降价信息
     * @return \think\response\Json
     */
    public function getCutPrice(Request $request){
        $user = $request->user;
        $uid = $user["uid"];
        $UserColl = new UserCollectModel();
        $list = $UserColl->getCutPrice($uid,3);

        return backSuccess($list);
    }

    /**
     * 留言消息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getMessage(Request $request){
        $user = $request->user;
        $uid = $user["uid"];
       // $UCMessage = new UserCarMessageModel();
       // $list = $UCMessage->getUserReply($uid,5);

        $uc=UserCarModel::field("id,car_id,series_id,vin,price,mileage,card_time,img_list,head_img")
            ->where('status',UserCarModel::SHOW_STATUS)
            ->where("user_id",$uid)
            ->order("lastreply_time desc")
            ->paginate(10)->toArray();

        $carMsgCount=0;
        $list=[];
        foreach ($uc["data"] as $vo){
            $series = CarSeriesModel::field('thumb,series_name')->where('series_id', $vo['series_id'])->find();
            if($vo['car_id']){
                $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$vo['car_id'])->find();
                $vo['car_name'] = $car->car_name;
                $vo['series_max'] = $car->series_max;
            }

            if(!empty($vo['vin'])){
                $carVin=CarLicenseMoreModel::field("sale_name")->where('vin','=',$vo['vin'])->find();
                $vo['car_name']=$carVin['sale_name'];
            }

            $vo['series_name'] = $series['series_name'];
            $vo['series_thumb'] = $series['thumb'];
            $vo['img_list']=json_decode($vo['img_list'],true);

            $UAM=UserActionModel::where('link_id',$vo['id'])
                ->where('type',0)
                ->order('status asc,create_time desc')
                ->limit(20);
            $lists=$UAM->select()->toArray();

            $vo['list']=[];
            foreach ($lists as $ac){
                $u=MemberModel::field('mobile')->find($ac["user_id"]);
                $ac["mobile"]=substr_replace($u['mobile'],'****',3,4);

                if($ac["msg_id"]>0){
                    $uic=UserCarMessageModel::field('pid,content')->find($ac["msg_id"]);
                    if($uic){
                        $ac["pid"]=$uic->pid;
                        //$ac["content"]= mb_substr($uic->content, 0, 5);
                        $ac["content"]= $uic->content.'...';
                    }
                }

                $vo['list'][]=$ac;
            }

            $list[]=$vo;

            $UAM->update(['status'=>1]);
        }

        return  backSuccess($list);
    }

    /**
     * 文章留言
     * @param Request $request
     * @return \think\response\Json
     */
    public function sendArticleMsg(Request $request){
        $id = $request->id;
        $content = $request->content;
        $pid = $request->pid;
        $user = $request->user;
        $uid = $user['uid'];


        $art = new ArticleMessageModel();
        $res = $art->addArticle($id,$uid,$content,$pid);
        if($res["status"] == 1){
          return backSuccess("","ok");
        } else {
            return backError($res["msg"]);
        }

    }

    /**
     * 收藏文章
     * @param Request $request
     * @return \think\response\Json
     */
    public function articleCollect(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $user_id = $request->user['uid'];

        $M = new ArticleCollectModel();

        $info=ArticleCollectModel::where('article_id',$id)
            ->where('user_id',$user_id)
            ->find();
        if($info) {
            $res = $info->delete();

            $status['status'] = $res;

            UserAction::del($user_id,$id,1,'collect');
        }else{
            $data = [
                'article_id' => $id,
                'user_id' => $user_id
            ];
            $status = $M->adds($data);
            UserAction::adds($user_id,$id,1,'collect');
        }

        if ($status['status']) {
            return backSuccess();
        } else {
            return backError($status['msg']);
        }
    }

    /**
     * 文章点赞
     * @param Request $request
     * @return \think\response\Json
     */
    public function articleGood(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $user_id = $request->user['uid'];

        $info = ArticleModel::get($id);

        if (empty($info) || empty($user_id)) {
            return backError('参数错误！');
        }

        $check=UserAction::checkGood($user_id,$id,1);

        if($check){
            $info->good_numb = $info->good_numb - 1;
            UserAction::del($user_id,$id,1,'good');
        }else{
            $info->good_numb = $info->good_numb + 1;
            UserAction::adds($user_id,$id,1,'good');
        }
        $status = $info->save();

        if ($status) {
            return backSuccess($info->good_numb);
        } else {
            return backError('参数错误！');
        }
    }

    /**
     * 详情指定文章用户留言列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMessageList(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $msg = new ArticleMessageModel();

        $list = $msg->getUserList($id);

        return backSuccess($list);
    }

    /**
     * 用户留言点赞
     * @param Request $request
     * @return \think\response\Json
     */
    public function goodMsg(Request $request)
    {
        if (empty($request->id)) {
            return backError('参数错误！');
        }

        $id = $request->id;
        $ip = $request->ip();
        $user_id = $request->user['uid'];

        $t = Cache::get($ip . "a_" . $id);
        if (!empty($t) && time() - $t <= (60 * 60 * 24)) {
            return backError('请勿频繁操作！');
        } else {
            Cache::set($ip . "a_" . $id, time(), 60 * 60 * 24);
        }

        $info = ArticleMessageModel::get($id);

        if (empty($info) || empty($user_id)) {
            return backError('参数错误！');
        }

        $check=UserAction::checkGood($user_id,0,1,$id);

        if($check){
            $info->good_numb = $info->good_numb - 1;
            UserAction::del($user_id,0,1,'good',$id);
        }else{
            $info->good_numb = $info->good_numb + 1;
            UserAction::adds($user_id,0,1,'good',$id);
        }
        $status = $info->save();

        if ($status) {
            return backSuccess($info->good_numb);
        } else {
            return backError('参数错误！');
        }
    }
}
